package com.huiyeji.dynamic.core.handler;

import com.huiyeji.dynamic.core.DynamicContext;
import com.huiyeji.dynamic.core.DynamicObject;
import com.huiyeji.dynamic.core.builder.DynamicBuilder;
import com.huiyeji.dynamic.core.exception.DynamicStatementExecuteException;
import com.huiyeji.dynamic.core.handler.PrefixHandler;

public class DynamicBuilderPrefixHandler implements PrefixHandler {

    private final String returnName;

    private final String prefixName;

    public DynamicBuilderPrefixHandler(String prefixName, String returnName) {
        this.returnName = returnName;
        this.prefixName = prefixName;
    }

    @Override
    public void preHandle(DynamicContext context) {

    }

    @Override
    public void postHandle(DynamicContext context) {
        if (!context.getFactory().containsDynamicObject(prefixName)){
            throw new DynamicStatementExecuteException("prefix post handler error : dynamic object builder 【"+prefixName+"】 not found !");
        }
        DynamicObject dynamicBuilderObject = context.getFactory().getDynamicObject(prefixName);
        Object object = dynamicBuilderObject.getObject();
        if (!(object instanceof DynamicBuilder)){
            throw new DynamicStatementExecuteException("prefix post handler error : dynamic object 【"+prefixName+"】 is not a DynamicBuilder !");
        }
        DynamicBuilder builder = (DynamicBuilder) object;
        DynamicObject dynamicObject = builder.build(context.getObject(returnName));
        if (dynamicObject != null){
            dynamicObject.setDynamicObjectName(returnName);
            context.getFactory().registerDynamicObject(dynamicObject);
        }
    }
}
